<?php
/**
 * Function: Swoole WebSocket 服务启动
 * Description:
 * Abo 2018/10/11 12:45
 * Email: abo2013@foxmail.com
 */
class SwooleWobSocket
{
    public $ws;

    // 启动Swoole
    public function start()
    {
        $this->ws = new swoole_websocket_server("0.0.0.0", 9502);

        // 静态资源返回 http://127.0.0.1:9502/ws_client.html
        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => __DIR__ . '/js',
        ]);

        //监听WebSocket连接打开事件
        $this->ws->on('open', function ($ws, $frame) {
            $ws->push($frame->fd, $frame->fd . ' client is connecting' . PHP_EOL);
        });

        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
            $ws->push( $frame->fd, "{$frame->fd} Message: {$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}" . PHP_EOL );
        });

        //监听WebSocket主动推送消息事件
        $this->ws->on('request', function (swoole_http_request $request, swoole_http_response $response) {
            $this->info( 'client is PushMessage' . var_export( $request->post['scene'], true ) );

            //global $server;//调用外部的server
            // $server->connections 遍历所有websocket连接用户的fd，给所有用户推送
            foreach ( $this->ws->connections as $fd ) {
                $this->ws->push( $fd, $request->post['scene'] );
            }
        });

        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            $ws->push( "client-{$fd} is closed" . PHP_EOL );
        });

        $this->ws->start();
    }

    // 消息记录
    private function info( $msg = '' )
    {
        if ( !$msg ) {
            return false;
        }

        return file_put_contents(
            __DIR__ . '/logs/' . date( 'm-d' ) . 'swoole_ws.log',
            $msg . PHP_EOL,
            FILE_APPEND
        );
    }
}

// php7 public/swoole_ws_server.php
( new \SwooleWobSocket() )->start();